# Define here the models for your spider middleware
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html
import random
import time

from scrapy import signals
# useful for handling different item types with a single interface
from itemadapter import is_item, ItemAdapter
from scrapy.downloadermiddlewares.useragent import UserAgentMiddleware
from scrapy.http import HtmlResponse
from selenium.webdriver.chrome.options import Options
from user_agent import generate_user_agent
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


class EastmoneySpiderMiddleware:
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the spider middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_spider_input(self, response, spider):
        # Called for each response that goes through the spider
        # middleware and into the spider.

        # Should return None or raise an exception.
        return None

    def process_spider_output(self, response, result, spider):
        # Called with the results returned from the Spider, after
        # it has processed the response.

        # Must return an iterable of Request, or item objects.
        for i in result:
            yield i

    def process_spider_exception(self, response, exception, spider):
        # Called when a spider or process_spider_input() method
        # (from other spider middleware) raises an exception.

        # Should return either None or an iterable of Request or item objects.
        pass

    def process_start_requests(self, start_requests, spider):
        # Called with the start requests of the spider, and works
        # similarly to the process_spider_output() method, except
        # that it doesn’t have a response associated.

        # Must return only requests (not items).
        for r in start_requests:
            yield r

    def spider_opened(self, spider):
        spider.logger.info("Spider opened: %s" % spider.name)


class EastmoneyDownloaderMiddleware:
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the downloader middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_request(self, request, spider):
        # Called for each request that goes through the downloader
        # middleware.

        # Must either:
        # - return None: continue processing this request
        # - or return a Response object
        # - or return a Request object
        # - or raise IgnoreRequest: process_exception() methods of
        #   installed downloader middleware will be called
        return None

    def process_response(self, request, response, spider):
        # Called with the response returned from the downloader.

        # Must either;
        # - return a Response object
        # - return a Request object
        # - or raise IgnoreRequest
        return response

    def process_exception(self, request, exception, spider):
        # Called when a download handler or a process_request()
        # (from other downloader middleware) raises an exception.

        # Must either:
        # - return None: continue processing this exception
        # - return a Response object: stops process_exception() chain
        # - return a Request object: stops process_exception() chain
        pass

    def spider_opened(self, spider):
        spider.logger.info("Spider opened: %s" % spider.name)


class EastmoneyAgentMiddleware(UserAgentMiddleware):
    '''
    设置User-Agent
    '''

    def __init__(self, user_agent):
        self.user_agent = user_agent

    @classmethod
    def from_crawler(cls, crawler):
        return cls(
            user_agent=crawler.settings.get('MY_USER_AGENT')
        )

    def process_request(self, request, spider):
        agent = random.choice(self.user_agent)
        request.headers['User-Agent'] = generate_user_agent()


class SeleniumMiddleware:
    # 当下载器中间件开始工作时，自动打开一个浏览器
    def __init__(self):
        self.driver = webdriver.Chrome()

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        # 下面这一行需要手动添加，作用是调用关闭浏览器的函数
        crawler.signals.connect(s.spider_closed, signal=signals.spider_closed)
        return s

    # 每当爬虫文件向目标网址发送一次请求都会调用这个函数，用处就是返回该网址的源码
    def process_request(self, request, spider):
        self.driver.get(request.url)  # 使用浏览器打开请求的URL
        time.sleep(2)
        body = self.driver.page_source  # 获取网页HTML源码

        # -------1、开始：为了爬取沪深300数据，在总览表实现点击下一页功能，获取下一页信息
        if '#hs_a_board' in request.url:
            for i in range(1, 15):
                next = self.driver.find_element(by=By.XPATH, value='//*[@id="main-table_paginate"]/a[2]')
                next.click()
                time.sleep(2)
                body = body + self.driver.page_source
        # -------1、结束：为了爬取沪深300数据，在总览表实现点击下一页功能，获取下一页信息

        # -------2、开始：为了爬取全球股票数据，在总览表实现点击下一页功能，获取下一页信息
        if '#global_asia' in request.url or '#global_euro' in request.url:
            guangao = self.driver.find_elements(by=By.XPATH, value='/html/body/div[5]/div[2]/span')
            if guangao:
                guangao[0].click()
                time.sleep(2)
            next = self.driver.find_element(by=By.XPATH, value='//*[@id="main-table_paginate"]/a[2]')
            if next :
                next.click()

            time.sleep(2)
            body = body + self.driver.page_source
        # -------2、结束：为了爬取全球股票数据，在总览表实现点击下一页功能，获取下一页信息

        return HtmlResponse(url=self.driver.current_url, body=body, encoding='utf-8', request=request)

    def process_response(self, request, response, spider):
        return response

    def process_exception(self, request, exception, spider):
        pass

    def spider_opened(self, spider):
        spider.logger.info("Spider opened: %s" % spider.name)

    # 该函数需要手动添加，作用是关闭浏览器

    def spider_closed(self, spider):
        self.driver.close()
        spider.logger.info("Spider closed: %s" % spider.name)
